<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Api\Controller;
use Think\Controller\RestController;

/**
 * api请求接口
 * 
 */
class WorksController extends RestController {
	
    protected function _initialize()
    {
        $path="./Runtime/Logs/Api/api_".date('Ymd').".log";        
        $data=array($_REQUEST,$_FILES);   
        $logMsg=json_encode($data);
        error_log($logMsg.PHP_EOL,3,$path);
    }
	
	/**
	 * 作品查看申请	6027
	 * 提交参数方式	post
	 * 
	 */
	 public function lookApply(){
    	if($this->_method != 'post'){
            $this->ajaxReturn($this->errorReturn('访问方式错误'));
        }
        //$_POST['workId']=7102;$_POST['memberId']=441;
	 	//作品id
	 	$workid=I('post.workId','0','intval');
		//申请人id
		$memberid=I('post.memberId','0','intval');
		//备注
		$remarks=I('post.reason','','string');
		
		if($workid == 0 && $memberid==0){
			$this->ajaxReturn($this->errorReturn('参数错误'));
		}
		
		//根据用户id获取用户信息
		$member=D('Common/Member');
		$return=$member->query_ums_member_bay($memberid);
		if(empty($return)){
			$this->ajaxReturn($this->errorReturn('用户不存在'));
		}
		if($return['status']==2){
			$this->ajaxReturn($this->errorReturn('用户已禁用'));
		}
		//根据作品id获取作品信息
		$works=D('Common/Works');
		$list=$works->query_blog_works_bay($workid);
		if(empty($list)){
			$this->ajaxReturn($this->errorReturn('没有找到作品'));
		}
		
		$works_auth=D('Common/WorksAuth');
		//查看用户是否已申请		
		$query_works_auth=$works_auth->query_blog_works_auth_bay($memberid,$workid);
		if(count($query_works_auth)==3){
			$this->ajaxReturn($this->successReturn('','已申请多次,请与平台客服联系'));
		}
		//获取用户最新的一条申请数据
		$works_auth_newest=$works_auth->newest_blog_works_auth_bat($memberid,$workid);
		$frequency=1;
		if(!empty($works_auth_newest)){
			switch ($works_auth_newest['apply_status']) {
				case '1':
					$this->ajaxReturn($this->successReturn('','审核中，请耐心等待'));
					break;
				case '2':
					$this->ajaxReturn($this->successReturn('','审核成功，无需在申请'));
					break;
				case '-1':
					if($works_auth_newest['frequency']==3){
						$this->ajaxReturn($this->successReturn('','已申请多次,请与平台客服联系'));
					}					 
					break;				
			}
			$frequency=	$works_auth_newest['frequency']+1;
			
		}
		//添加申请查看作品数据
		$data=array(
			'works_id'     => $workid,//作品id
			'apply_uid'    => $memberid,//申请用户id
			'works_uid'    => $list['works_memberid'],//作品用户id
			'apply_phone'  => $return['username'],//手机
			'apply_name'   => $return['nickname'],//用户名
			'apply_status' => 1,//审核状态:1审核中,2审核成功,-1审核失败,10允许查看所有作品
			'frequency'	   =>$frequency,	
			'apply_mode'   => 1,//来源:1申请,2用户导入
		);
		if($frequency >1){
			if($remarks==''){
				$this->ajaxReturn($this->errorReturn('再次申请需填写备注'));
			}
			$data['examine_reason']=$remarks;
		}

		$works_auth_id=$works_auth->add_blog_works_auth_bay($data);
		if(empty($works_auth_id)){
			$this->ajaxReturn($this->errorReturn('申请查看失败'));
		}	
		
		$this->ajaxReturn($this->successReturn('','申请查看请求成功'));	
		
	 }

	
	/**
	 * 作品查看审核	6026
	 * 提交参数方式	post
	 */
	 public function review(){
    	if($this->_method != 'post'){
            $this->ajaxReturn($this->errorReturn('访问方式错误'));
        }
       // $_POST['worksAuthId']=220;
       // $_POST['memberId']=2186;
       // $_POST['reviewStatus']=0;
 
	 	//作品权限申请id
	 	$works_auth_id=I('post.worksAuthId','0','intval');
		//作品用户id  works_uid
		$memberid=I('post.memberId','0','intval');
		$phone=I('post.phone');
		//审核状态：0允许查看该作品，1允许查看所有作品，2拒绝，-1删除  
		$reviewstatus=I('post.reviewStatus','','intval');
		//申请标志
		$refuseStatus=I('post.refuseStatus','','intval');
	
		//审核备注
		$remarks=I('post.refuseStr','','string');
		if($works_auth_id == 0 && $memberid==0){
			$this->ajaxReturn($this->errorReturn('参数错误'));
		}
		if(!in_array($reviewstatus,array('1','0','2','-1'))){
			$this->ajaxReturn($this->errorReturn('status参数错误'));
		}
		
		if($reviewstatus=="-1" && !$refuseStatus){
			if(!in_array($refuseStatus, array('1','2','3'))){
				if($refuseStatus=='3' && !$remarks){
					$this->ajaxReturn($this->errorReturn('refuseStr参数错误'));
				}
				$this->ajaxReturn($this->errorReturn('refuseStatus参数错误'));
			}
			    						
		}

		//判断用户是否有权限审核
		$works_auth=D('Common/WorksAuth');
		$works_auth_list=$works_auth->query_blog_works_auth_id_bay($works_auth_id,$memberid);
		if(empty($works_auth_list)){
			$this->ajaxReturn($this->errorReturn('您无法操作该数据'));
		}
		if(!$works_auth_list['works_id']){
		    $this->ajaxReturn($this->successReturn('','无法指定作品'));
		}
		
		
		//判断作者下作品是否还存在申请且权限为可以查看所有
		if($works_auth_list['apply_status']!=10){
			$there_exist_list=$works_auth->get_blog_works_auth_there_exist($memberid,$works_auth_list['apply_uid']);
			if(!empty($there_exist_list)){
				$this->ajaxReturn($this->errorReturn('该用户已有作品权限为允许查看所有'));
			}			
		}
		
		
		//修改申请作品权限状态 0允许查看该作品，1允许查看所有作品，2拒绝，-1删除
		switch ($reviewstatus) {
					case '0':
					$state=2;
				break;
					case '1':
					$state=10;
				break;
					case '2':
						if($refuseStatus==3 && $remarks==''){
							$this->ajaxReturn($this->errorReturn('请填写备注信息'));
						}
					$state=-1;
				break;
					case '-1':
					$state=-2;	
				break;			
		}
		switch ($refuseStatus){
		    case 1:$reason="不公开作品";break;
		    case 2:$reason="联系我$phone";break;
		    case 3:$reason=$remarks;break;
		}
		
		$state_works_auth=$works_auth->modify_blog_works_auth_bay_state($works_auth_id,$state,$reason);
		if(empty($state_works_auth)){
			$this->ajaxReturn($this->errorReturn('审核失败'));
		}
		
		$this->ajaxReturn($this->successReturn('','审核成功'));

		 	
	 }




	/**
	 * 作品查看申请列表		6028
	 * 提交参数方式	post
	 */
	 public function lookApplyList(){
    	 if($this->_method != 'post'){
            $this->ajaxReturn($this->errorReturn('访问方式错误'));
        } 
        // $_POST['pageIndex']=2;
		// $_POST['memberId']=2;
	 	//作品id
	 	$workid=I('post.workId','0','intval');
		//作品用户id  works_uid
		$memberid=I('post.memberId','0','intval');
		if((int)$memberid <= 0){
			$this->ajaxReturn($this->errorReturn('参数错误'));
		}
		
        $pageIndex = I('post.pageIndex');
        if(!is_positive_int($pageIndex)){
            $_GET['p'] = 1;
        }else{
            $_GET['p'] = $pageIndex;
        }
		
		//根据用户id获取用户信息
		$member=D('Common/Member');
		$return=$member->query_ums_member_bay($memberid);
		if(empty($return)){
			$this->ajaxReturn($this->errorReturn('用户不存在'));
		}
		if($return['status']==2){
			$this->ajaxReturn($this->errorReturn('用户已禁用'));
		}
		
		//判断作品是否属于该用户
		$works=D('Common/Works');
		if($workid > 0){
			$works_list=$works->see_blog_works_bay($memberid,$workid);
			if(empty($works_list)){
				$this->ajaxReturn($this->errorReturn('没有权限操作该作品'));
			}
		}		
		
		//获取申请列表
		$works_auth=D('Common/WorksAuth');
		$works_auth_list=$works_auth->query_blog_works_auth_all($memberid,$workid);

		//返回值
		$data=array();
		foreach ($works_auth_list['tag'] as $k => $v) {
			$works_return=$works->query_blog_works_bay($v['works_id']);
            //if($works_return){
                $WorksContent_return=D('Common/WorksContent')->query_blog_works_pic($v['works_id']);
                $data['list'][$k]['workName']=$works_return['works_title'];//作品名称
                $data['list'][$k]['coverUrl']=add_host_prefix($WorksContent_return['img_intro']);//作品封面
                //$data['list'][$k]['coverUrl']= C('PIC_DOMAIN').$WorksContent_return['img_intro'].'-w400';//作品封面
                $data['list'][$k]['userName']=$v['apply_name'];//申请人用户名
                $data['list'][$k]['phone']=$v['apply_phone'];//申请人手机
                $data['list'][$k]['date']=date('Y/m/d H:i',$v['create_time']);//申请时间
                $data['list'][$k]['worksId']=$v['works_id'];//作品id
                $data['list'][$k]['worksAuthId']=$v['id'];//权限表id
                $data['list'][$k]['frequency']=(int)$v['frequency'];//申请的备注
                $data['list'][$k]['reason']=$v['examine_reason'];//用户申请备注
                ////审核状态：-1审核中，0允许查看当前作品，1允许查看所有作品，2拒绝查看
                if($v['apply_status']==1){
                    $data['list'][$k]['status']=-1;
                }elseif($v['apply_status']==2){
                    $data['list'][$k]['status']=0;
                }elseif($v['apply_status']==-1){
                    $data['list'][$k]['status']=2;
                }elseif($v['apply_status']==10){
                    $data['list'][$k]['status']=1;
                }
            
            //}
			
			//$data[$k]['status']=$works_auth_list['apply_status'];
		}
		
		
		
		$data['pageCount']=$works_auth_list['pageCount'];
		$data['pageIndex']=$works_auth_list['pageIndex'];
		$this->ajaxReturn($this->successReturn($data));	 	
	 }
	 
	//系统首页
    public function ad(){
    	$_POST['id']=1;

        $category = D('Category')->getTree();
        $lists    = D('Document')->lists(null);

        $this->assign('category',$category);//栏目
        $this->assign('lists',$lists);//列表
        $this->assign('page',D('Document')->page);//分页

                 
        $this->display();
    }


    
    
   /**
    * 成功返回(API 专用)
    * @param $msg
    * @param string $extend
    * @return array
    */
    function successReturn($data = [],$msg='成功',$sign=true)
    {
        $return = array(
            'code' => 1,
            'desc' => $msg,
        );
        if($sign){
          if (is_array($data) && ($data == [])) {
            // break;
          } else {
            $return['data'] = $data;
          }
        }
        return $return;
    }
    
    /**
    * 错误返回(API 专用)
    * @param $msg
    * @param string $extend
    * @return array
    */
    function errorReturn($msg='失败', $extend = '')
    {
        $return = array(
            'code' => 0,
            'desc' => $msg
        );

        is_array($extend) && ($return = array_merge($return, $extend));
        return $return;
    }
}
